package repo

import (
	"io"
	"os"
	"path/filepath"
	"time"

	"gitee.com/linxing_3/sr-core/utils/crypto"
	"gitee.com/mkwchecking/sr-admin/apps/knowledge/conf"
	"gitee.com/mkwchecking/sr-admin/apps/knowledge/entity"
	"github.com/gin-gonic/gin"
)

func NewOss() *OssRepo {
	return &OssRepo{
		cfg: conf.Conf.Oss,
	}
}

type OssRepo struct {
	cfg *conf.Oss
}

func (r *OssRepo) ResaveFormatFile(c *gin.Context) (*entity.KnoDoc, error) {
	file, err := c.FormFile("file")
	if err != nil {
		return nil, err
	}

	uploadId := crypto.MD5Str(time.Now().String())
	ext := filepath.Ext(file.Filename)
	sourcePath := filepath.Join(r.cfg.Data, uploadId[:2], uploadId+ext)
	if err = c.SaveUploadedFile(file, sourcePath); err != nil {
		return nil, err
	}

	return &entity.KnoDoc{
		SourcePath: sourcePath,
		Title:      file.Filename,
	}, nil
}

func (r *OssRepo) GetFile(sourcePath string) (io.Reader, error) {
	path := filepath.Join(r.cfg.Data, sourcePath)
	stat, err := os.Stat(path)
	if err != nil {
		return nil, err
	} else if stat.IsDir() {
		return nil, os.ErrInvalid
	}

	return os.Open(path)
}
